/**
 * 角色相关
 */
/**
 * role/save 角色保存
 * role/resetname 更改角色名称
 * role/removerole 删除角色
 * role/findbyname 根据名查找角色
 * role/list 查找角色列表
 */

const express = require('express');
const router = express.Router();
// 引入操作的模型 
const RoleModel = require('../db/RoleModel');
const Fun = require("../middlewares/Fun")
const moment = require('moment');
const now = () => {
    return moment().format('YYYY-MM-DD HH:mm:ss')
}
const UserModel = require('../db/UserModel');//用户模型
router.post('/hadnamed', function (req, res, next) {
    if (!req.body.name) {
        return res.json({ code: 201, mes: '缺少必填信息！' });
    }

    RoleModel.findOne({ name: req.body.name }).then((data) => {
        if (data) {
            return res.json({ code: 201, mes: '该名称已经存在！' });
        } else {
            return res.json({ code: 200, mes: '该名称可用！' });
        }
    }).catch(() => {
        return res.json({ code: 201, mes: '发生意外错误！' })
    });

});


// POST /save 增加角色  
router.post('/save', function (req, res, next) {
    // 获取条件
    let user = req.user;
    let pare;
    if (!req.body.state || !req.body.name) {
        return res.json({ code: 201, mes: '缺少必填信息！' });
    }
    pare = {
        id: user._id,
        name: user.name,
        roles: user.role,
        ip: req.ip.replace(/::ffff:/, ''),
        time: now(),
        Operationcontent: "角色创建成功"
    };
    const role = new RoleModel({ name: req.body.name, state: req.body.state });

    RoleModel.find({ name: req.body.name }).then((data) => {
        if (data.length != 0) { return res.json({ code: 201, mes: '角色名称已经存在！' }); }
        else {
            return role.save().then(() => {
                Fun.saveLog(pare);
                return res.json({ code: 200, mes: '角色创建成功！' })
            }).catch((err) => {
                console.log(err);
                pare.time = now();
                pare.Operationcontent = "角色创建失败";
                Fun.saveLog(pare);
                return res.json({ code: 201, mes: '发生意外错误！' })
            })
        }
    }).catch((err) => {
        console.log(err);
        return res.json({ code: 201, mes: '发生意外错误！' })
    });
});
// 更新角色
router.post('/update', function (req, res, next) {
    // 更改密码的判断需要额外处理
    const set = req.body;
    const id = req.body.id;
    let user = req.user;
    if (!req.body.tree) {
        req.body.tree = []
    }
    RoleModel.findById(id).then(data => {
        if (data == null) {
            return res.json({ code: 201, mes: '传入id错误' });
        } else {
            return RoleModel.update({ _id: id }, { $set: set }).then(datas => {
                return UserModel.update({ role: id }, { $set: { jurisdiction: req.body.tree } }, { multi: true }).then(users => {
                    Fun.saveLogs(user, req.ip.replace(/::ffff:/, ''), "角色更新成功");
                    return res.json({ code: 200, mes: '更改成功' });
                })
            })
        }
    }).catch(function () {
        Fun.saveLogs(user, req.ip.replace(/::ffff:/, ''), "角色更新失败");
        return res.json({ code: 201, mes: '发生意外错误！' });
    });
});

// 查找所有科室
router.get('/list', function (req, res, next) {
    RoleModel.find().then((roles) => {
        return res.json({ code: 200, roles });
    }).catch(() => {
        return res.json({ code: 201, mes: '发生意外错误！' });
    });
});
// 查找指定角色接口
router.get('/one/:id', function (req, res, next) {
    const id = req.params.id;
    RoleModel.findById(id).then((role) => {
        return res.json({ code: 200, role });
    }).catch(() => {
        return res.json({ code: 201, mes: '发生意外错误！' });
    });
});
// 删除角色接口
router.post('/delete', function (req, res, next) {
    const id = req.body.id;
    let user = req.user;
    RoleModel.remove({ _id: id }).then(() => {
        Fun.saveLogs(user, req.ip.replace(/::ffff:/, ''), "删除角色成功");
        return res.json({ code: 200, mes: '删除成功！' });
    }).catch(() => {
        Fun.saveLogs(user, req.ip.replace(/::ffff:/, ''), "删除角色失败");
        return res.json({ code: 201, mes: '发生意外错误！' });
    });
});

//判断角色下面是否有关联的医生
router.post('/matching', (req, res) => {
    const id = req.body.id;
    if (!id) {
        return res.json({
            code: 201,
            mes: "缺少必要参数."
        })
    };
    let user = req.user;
    return UserModel.find({ role: id }).then(users => {
        if (users.length > 0) {
            return res.json({ code: 200, mes: '存在关联医生' });
        } else {
            return res.json({ code: 201, mes: '不存关联医生' });
        }
    }).catch(function () {
        return res.json({ code: 201, mes: '发生意外错误！' });
    });
});

//判断所属角色下是否有员工存在
router.get("/istThere", (req, res) => {
    let { rooid } = req.query;
    if (!rooid) {
        return res.json({
            code: 203,
            mes: "参数错误!"
        })
    }
    UserModel.find({ role: rooid }).then(data => {
        if (data.length > 0) {
            return res.json({
                code: 201,
                mes: "该角色下存在医生!"
            })
        } else {
            return res.json({
                code: 200,
                mes: "该角色下不存在医生!"
            })
        }
    }).catch(err => {
        return res.json({
            code: 202,
            mes: "发生错误!",
            err
        })
    });
});

module.exports = router;
